<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--数据列表主工作区-->
    <el-card>
      <!--搜索框和添加按钮-->
      <el-row :gutter="20" :class="['search-bar']" >
        <el-col :span="8">
          <el-input placeholder="请输入搜索内容" class="input-with-select" v-model="pageReqParams.query">
            <el-button slot="append" icon="el-icon-search" @click="handleSearchButtonClick()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleAddButtonClick()">添加</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="danger" @click="handleBatchDeleteButtonClick()">批量删除</el-button>
        </el-col>
      </el-row>

      <!--用户列表-->
      <el-table
        :data="pageInfo.list"
        border
        stripe
        @selection-change="handleSelectionChangeInTable"
        style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          prop="id"
          label="ID"
        >
        </el-table-column>

        <el-table-column
          prop="name"
          label="角色"
        >
        </el-table-column>
        <el-table-column
          prop="info"
          label="角色描述">
        </el-table-column>
        <el-table-column
          prop="modifiedTime"
          label="最后修改时间"
        >
        </el-table-column>

        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit"
                         @click="handleModifyButtonClick(scope.row)"></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete"
                         @click="handleDeleteButtonClick(scope.row)"></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting"
                         @click="handlePrivilegesButtonClick(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!--数据列表分页-->
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageNumberChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="pageSizes"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
      </el-pagination>
    </el-card>
    <!--添加对话框-->
    <el-dialog title="添加"
               :center="true"
               :visible.sync="addDialogVisible" width="50%">

      <el-form>
        <el-form-item label="角色名称">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.info"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelAddButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAddButtonClick()">确 定</el-button>
      </div>

    </el-dialog>
    <!--修改对话框-->
    <el-dialog title="修改"
               :center="true"
               :visible.sync="modifyDialogVisible" width="50%">

      <el-form>
        <el-form-item label="角色名称">
          <el-input v-model="currentModifyingData.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="currentModifyingData.info"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelModifyButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmModifyButtonClick()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配权限"
               :center="true"
               :visible.sync="distributionPrivilegeDialogVisible" width="50%">
      <el-row :class="['gray-bgc']">
        角色: {{currentModifyingData.name}}
      </el-row>
      <el-row>


        <el-tree ref="privilegeTreeRef"
                 :data="privileges"
                 show-checkbox
                 check-strictly
                 node-key="id"
                 default-expand-all
                 :props="defaultProps"

                 :default-checked-keys="privilegeIdList"
                 @check="handleCheckClick"
                 @check-change="handlePrivilegesTreeCheckChange">
        </el-tree>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDistributionPrivilegeButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAddPrivilegesButtonClick()">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {mapState} from "vuex"
  export default {
    name: "Roles",
    data() {
      return {

        // 分页请求时要携带的参数
        pageReqParams: {
          query: '',
          pageNum: 1,
          pageSize: 5
        },
        // 分页信息
        pageInfo: {
          pageNum: 0,
          pageSize: 0,
          total: 0,
          totalPage: 0,
          list: []
        },
        // 分页的大小常量列表
        pageSizes: [5, 10, 20, 30, 50, 100],
        // 添加对话框显示开关
        addDialogVisible: false,
        // 修改对话框显示开关
        modifyDialogVisible: false,

        // 分配权限对话框
        distributionPrivilegeDialogVisible: false,

        // 添加对话框中的表单数据
        addForm: {
          name:'',
          info:''
        },



        // 表单的宽度变量
        formLabelWidth: 500,

        //当前正在修改的角色，或在分配权限的角色
        currentModifyingData: {},

        //表中选中行的ID列表
        idsSelection:[],

        //当前角色的权限ID列表
        privilegeIdList:[],

        // 树型组件的字段映射
        defaultProps: {
          children: 'children',
          label: 'name'
        }

      }
    },

    computed:{
      ...mapState({
        privileges: state=>state.rbac.privileges
      })
    },

    created() {
      this.getPageFunction();
    },
    methods: {



      //打开修改对话框
      handleModifyButtonClick(row) {
        this.currentModifyingData = JSON.parse(JSON.stringify(row));
        // TODO 先去请求原始数据，然后显示对话框

        this.modifyDialogVisible = true;
      },

      // 确认修改
      async handleConfirmModifyButtonClick() {

        this.modifyDialogVisible = false;
        //TODO 发起修改请求
        this.api.__api__RolesUpdate(this.currentModifyingData)
          .then(data=>{
            this.getPageFunction();
            this.$message.success(data.message);
          }).catch(error=>{
          this.$message.error(error);
        })
      },

      // 删除
      async handleDeleteButtonClick(row) {

        const res = await this.$confirm('确定要删除?', "提示");
        if (res == 'confirm') {
          // TODO 发起删除请求
          this.api.__api__RolesDelete([row.id])
            .then(data=>{
              this.getPageFunction();
              this.$message.success(data.message);
            }).error(error=>null);
        } else {
          this.$message.info("已取消删除");
        }
      },

      handlePrivilegesButtonClick(row){
        this.currentModifyingData = row;
        this.api.__api__RolesPrivilegesIds(row.id)
          .then(data=>{
            this.privilegeIdList = data.data;
            this.distributionPrivilegeDialogVisible = true;
            console.log("ids===="+JSON.stringify(this.privilegeIdList));
            this.$nextTick(() => {
              this.$refs.privilegeTreeRef.setCheckedKeys(this.privilegeIdList);
            });
          }).catch(error=>null);

      },


      // 批量删除
      async handleBatchDeleteButtonClick(){
        if(this.idsSelection.length==0){
          this.$message.error("请先在表格中选中数据行");
          return;
        }
        const res = await this.$confirm('确定要删除?', "提示");
        if (res == 'confirm') {
          this.api.__api__RolesDelete(this.idsSelection)
            .then(data=>{
              this.getPageFunction();
              this.$message.success(data.message);
            }).catch(error=>null);
        }


      },

      //确认添加
      handleConfirmAddButtonClick() {
        //TODO 发起添加请求
        this.api.__api__RolesAdd(this.addForm)
          .then(data=>{
            this.addDialogVisible = false;
            this.getPageFunction();
            this.$message.success(data.message);
          }).catch(error=>{
          console.error(error);
          return null;
        });
      },

      //点击搜索
      handleSearchButtonClick() {
        this.getPageFunction();
      },

      //页大小改变
      handlePageSizeChange(size) {
        this.pageInfo.pageSize = size;
        this.pageReqParams.pageSize = size;
        this.getPageFunction();
      },

      //页码改变
      handleCurrentPageNumberChange(pageNum) {
        this.pageReqParams.pageNum = pageNum;
        this.getPageFunction();
      },

      //获取一页数据
      getPageFunction() {
        //TODO 发起分页请求
        this.api.__api__RolesPage(this.pageReqParams)
          .then(data => {
            this.pageInfo = data.data;
          }).catch(error => {
          console.log(error);
        })
      },

      //弹出添加对话框
      handleAddButtonClick() {
        this.addDialogVisible = true;
      },

      //取消添加
      handleCancelAddButtonClick() {
        this.addDialogVisible = false;
      },

      //取消修改
      handleCancelModifyButtonClick() {
        this.modifyDialogVisible = false;
      },



      handleSelectionChangeInTable(selection){
        this.idsSelection.length = 0 ;
        selection.forEach((item)=>this.idsSelection.push(item.id));
      },

      //取消分配权限
      handleCancelDistributionPrivilegeButtonClick(){
        this.distributionPrivilegeDialogVisible = false;
      },

      // 确认分配权限
      handleConfirmAddPrivilegesButtonClick(){
        const ids = this.$refs.privilegeTreeRef.getCheckedKeys();
        ids.push(...this.$refs.privilegeTreeRef.getHalfCheckedKeys());
        this.api.__api__RolesPrivilegesUpdate({roleId: this.currentModifyingData.id, privilegeIds:ids})
          .then(data => {
            this.currentModifyingData.privileges = data.data;
            this.$message.success(data.message);
            this.distributionPrivilegeDialogVisible = false;
          })
          .catch(error => {
            console.error(error);
          })
        this.privilegeIdList = [];
      },

      handlePrivilegesTreeCheckChange(){

      },

      handleCheckClick(item,status){
        const curNode = this.$refs.privilegeTreeRef.getNode(item.id);
        const keys = [];
        keys.push( ...status.checkedKeys );
        if(keys.indexOf(curNode.key)>=0){
          this.recursionParent(keys,curNode);
          this.recursionChildren(keys,curNode,true);
        }else{
          this.recursionChildren(keys,curNode, false);
        }
        this.$refs.privilegeTreeRef.setCheckedKeys(keys);

      },

      //递归设置子节点的状态,即父节点选中，子节点全部选中，父节点取消，子节点全部取消
      recursionChildren(keys,node,checked){

        if(node.childNodes){
          node.childNodes.forEach(child=>{
            const index = keys.indexOf(child.key);
            if(checked){
              if(index<0){
                keys.push(child.key);
              }
            }else{
              if(index >=0){
                keys.splice(index,1);
              }
            }
            if( child.childNodes ){
              this.recursionChildren(keys,child,checked);
            }
          })
        }
      },
      //递归设置父节点，子节点选中，则各级父节点全部选中
      recursionParent(keys,node){
        if(node.parent) {
          if (keys.indexOf(node.parent.key) < 0) {
            keys.push(node.parent.key);
          }
          this.recursionParent(keys,node.parent);
        }

      }





    }

  }
</script>

<style scoped>

  .el-pagination {
    margin: 5px;
  }


</style>
